<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            padding: 0;
            margin: 0;
        }
    </style>
    <script src="./tinymce/tinymce.min.js"></script>
    <script>
        tinymce.init({
            selector: 'textarea#full-featured',
            plugins: 'code print preview importcss searchreplace autolink autosave save directionality visualblocks visualchars fullscreen filemanager image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount imagetools textpattern noneditable help charmap emoticons',
            language: 'zh_CN',
            mobile: {
                plugins: 'print preview importcss searchreplace autolink autosave save directionality visualblocks visualchars fullscreen filemanager image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount textpattern noneditable help charmap quickbars emoticons'
            },
            menu: {
                tc: {
                    title: 'TinyComments',
                    items: 'addcomment showcomments deleteallconversations'
                }
            },
            menubar: 'file edit view insert format tools table tc help',
            toolbar: 'code | undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist | forecolor backcolor removeformat | pagebreak | charmap emoticons | fullscreen preview save print | filemanager image media pageembed template link anchor codesample | visualblocks searchreplace',
            autosave_ask_before_unload: true,
            autosave_interval: "30s",
            autosave_prefix: "{path}{query}-{id}-",
            autosave_restore_when_empty: false,
            autosave_retention: "2m",
            convert_urls: false,
            extended_valid_elements: 'span',
            image_advtab: true,
            image_class_list: [
                { title: 'None', value: '' },
                { title: 'Some class', value: 'class-name' }
            ],
            importcss_append: true,
            templates: [
                { title: 'New Table', description: 'creates a new table', content: '<div class="mceTmpl"><table width="98%%"  border="0" cellspacing="0" cellpadding="0"><tr><th scope="col"> </th><th scope="col"> </th></tr><tr><td> </td><td> </td></tr></table></div>' },
                { title: 'Starting my story', description: 'A cure for writers block', content: 'Once upon a time...' },
                { title: 'New list with dates', description: 'New List with dates', content: '<div class="mceTmpl"><span class="cdate">cdate</span><br /><span class="mdate">mdate</span><h2>My List</h2><ul><li></li><li></li></ul></div>' }
            ],
            template_cdate_format: '[Date Created (CDATE): %m/%d/%Y : %H:%M:%S]',
            template_mdate_format: '[Date Modified (MDATE): %m/%d/%Y : %H:%M:%S]',
            height: window.innerHeight,
            image_caption: true,
            quickbars_selection_toolbar: 'bold italic | quicklink h2 h3 blockquote filemanager quicktable',
            noneditable_noneditable_class: "mceNonEditable",
            toolbar_mode: 'inline',
            spellchecker_dialog: true,
            spellchecker_whitelist: ['Ephox', 'Moxiecode'],
            content_style: ".mymention{ color: gray; }",
            contextmenu: "link bold copy filemanager image",
            a11y_advanced_options: true,
            draggable_modal: true,
            branding: false,
            // 图片上传
            images_upload_handler: function (blobInfo, success, failure) {
                var xhr, formData;
                xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                xhr.open('POST', '/api/upload');

                xhr.onload = function() {
                    var json;
                    if (xhr.status != 200) {
                        failure('HTTP 异常: ' + xhr.status);
                        return;
                    }
                    json = JSON.parse(xhr.responseText);
                    if (!json || typeof json.location != 'string') {
                        failure('无效的 JSON: ' + xhr.responseText);
                        return;
                    }
                    success(json.location);
                };

                formData = new FormData();
                formData.append('file', blobInfo.blob(), blobInfo.filename());
                xhr.send(formData);
            },
            // 文件名和文件上传
            file_picker_callback: function(callback, value, meta) {
                if (meta.filetype == 'file' || meta.filetype == 'image') {
                    var input = document.createElement('input');
                    input.setAttribute('type', 'file');
                    input.setAttribute('accept', 'image/*');

                    input.onchange = function() {
                        var file = this.files[0];
                        var reader = new FileReader();

                        reader.onload = function() {
                            // 提交到后端处理
                            var xhr = new XMLHttpRequest();
                            xhr.withCredentials = false;
                            xhr.open('POST', '/api/upload');
                            xhr.onload = function() {
                                var json;
                                if (xhr.status != 200) {
                                    failure('HTTP Error: ' + xhr.status);
                                    return;
                                }
                                json = JSON.parse(xhr.responseText);
                                if (!json || typeof json.location != 'string') {
                                    failure('Invalid JSON: ' + xhr.responseText);
                                    return;
                                }
                                // 回调成功函数，并传入文件名
                                callback(json.location, { alt: file.name });
                            };

                            var formData = new FormData();
                            formData.append('file', file, file.name);
                            xhr.send(formData);
                        };
                        reader.readAsDataURL(file);
                    };
                    input.click();
                }
            },
            // 文件保存
            save_onsavecallback: function () {
            const content = tinymce.get('full-featured').getContent();
            const filename = prompt("请输入文件名（带扩展名）：", "saved_content.html");
            if (!filename) {
                alert("文件名不能为空");
                return;
            }
            fetch('/api/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ content: content, filename: filename })
            }).then(response => {
                if (response.ok) {
                    alert('已保存');
                } else {
                    alert('保存失败');
                }
            }).catch(error => {
                console.error('Error:', error);
                alert('保存出错');
            });
        }
        });
    </script>
</head>
<body>
<textarea id="full-featured"></textarea>
</body>
</html>
